<template>
  <div class="home-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <div class="logo">
          <h2>医捷通</h2>
        </div>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              <el-avatar :size="32" :style="{ backgroundColor: '#409EFF', color: 'white' }">
                {{ currentUser?.name?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="username">{{ currentUser?.name || '用户' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
                      <el-dropdown-menu>
          <el-dropdown-item command="profile">个人信息</el-dropdown-item>
          <el-dropdown-item v-if="isAdmin" command="admin" divided>系统管理</el-dropdown-item>
          <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
        </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 轮播图 -->
    <div class="carousel-section">
      <el-carousel height="200px" indicator-position="outside">
        <el-carousel-item v-for="item in carouselData" :key="item.id">
          <div class="carousel-item" :style="{ backgroundColor: item.bgColor }">
            <div class="carousel-content">
              <h3>{{ item.title }}</h3>
              <p>{{ item.content }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 快捷入口 -->
    <div class="quick-actions">
      <div class="action-grid">
        <el-card class="action-item" @click="goToDepartments" shadow="hover">
          <div class="action-content">
            <el-icon class="action-icon"><OfficeBuilding /></el-icon>
            <div class="action-text">科室查询</div>
            <div class="action-desc">查看医院科室信息</div>
          </div>
        </el-card>
        <el-card class="action-item" @click="goToAppointment" shadow="hover">
          <div class="action-content">
            <el-icon class="action-icon"><Calendar /></el-icon>
            <div class="action-text">预约挂号</div>
            <div class="action-desc">在线预约医生</div>
          </div>
        </el-card>
        <el-card class="action-item" @click="goToMyAppointments" shadow="hover">
          <div class="action-content">
            <el-icon class="action-icon"><Document /></el-icon>
            <div class="action-text">{{ isAdmin ? '系统管理' : isDoctor ? '我的病人' : '我的预约' }}</div>
            <div class="action-desc">{{ isAdmin ? '管理系统和用户' : isDoctor ? '查看挂号病人' : '查看预约记录' }}</div>
          </div>
        </el-card>
        <el-card class="action-item" @click="goToAIQuestion" shadow="hover">
          <div class="action-content">
            <el-icon class="action-icon"><ChatDotRound /></el-icon>
            <div class="action-text">AI问答</div>
            <div class="action-desc">智能健康咨询</div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 最近预约/我的病人/系统概览 -->
    <div class="recent-appointments" v-if="recentAppointments.length > 0 || isAdmin">
      <div class="section-header">
        <h3>{{ isAdmin ? '系统概览' : isDoctor ? '我的病人' : '最近预约' }}</h3>
        <el-button type="text" @click="goToMyAppointments">
          {{ isAdmin ? '系统管理' : '查看全部' }} <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      <el-card class="appointment-list" shadow="never">
        <!-- 管理员系统概览 -->
        <div v-if="isAdmin" class="admin-overview">
          <el-row :gutter="20">
            <el-col :span="6" v-for="stat in adminStats" :key="stat.title">
              <div class="stat-item">
                <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                  <el-icon><component :is="stat.icon" /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-value">{{ stat.value }}</div>
                  <div class="stat-title">{{ stat.title }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 医生和患者的预约列表 -->
        <div v-else>
          <div 
            v-for="appointment in recentAppointments" 
            :key="appointment.id"
            class="appointment-item"
            @click="viewAppointmentDetail(appointment.id)"
          >
            <div class="appointment-info">
              <div class="doctor-info">
                <el-avatar :size="40" class="doctor-avatar" :style="{ backgroundColor: '#409EFF', color: 'white' }">
                  {{ isDoctor ? appointment.patientName?.charAt(0) : appointment.doctorName?.charAt(0) }}
                </el-avatar>
                <div class="doctor-details">
                  <div class="doctor-name">
                    {{ isDoctor ? appointment.patientName : appointment.doctorName }}
                  </div>
                  <div class="department-name">
                    {{ isDoctor ? appointment.patientPhone : appointment.departmentName }}
                  </div>
                </div>
              </div>
              <div class="appointment-time">
                <el-icon><Clock /></el-icon>
                {{ appointment.appointmentDate }} {{ appointment.appointmentTime }}
              </div>
            </div>
            <el-tag 
              :type="getStatusType(appointment.status)" 
              size="small"
              class="appointment-status"
            >
              {{ getStatusText(appointment.status) }}
            </el-tag>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 健康提醒 -->
    <div class="health-tips">
      <div class="section-header">
        <h3>健康提醒</h3>
      </div>
      <el-card class="tips-content" shadow="never">
        <div class="tip-item">
          <el-icon class="tip-icon"><Sunny /></el-icon>
          <div class="tip-content">
            <div class="tip-title">春季养生</div>
            <div class="tip-desc">注意保暖，多喝水，适当运动</div>
          </div>
        </div>
        <div class="tip-item">
          <el-icon class="tip-icon"><Bell /></el-icon>
          <div class="tip-content">
            <div class="tip-title">定期体检</div>
            <div class="tip-desc">建议每年进行一次全面体检</div>
          </div>
        </div>
        <div class="tip-item">
          <el-icon class="tip-icon"><FirstAidKit /></el-icon>
          <div class="tip-content">
            <div class="tip-title">按时服药</div>
            <div class="tip-desc">高血压、糖尿病患者请按时服药</div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mockAPI } from '../utils/mockData'

export default {
  name: 'Home',
  setup() {
    const router = useRouter()
    const carouselData = ref([])
    const recentAppointments = ref([])
    const currentUser = ref(null)
    const isAdmin = ref(false)
    const isDoctor = ref(false)
    const adminStats = ref([])

    // 获取当前用户信息
    const userStr = localStorage.getItem('user')
    if (userStr) {
      currentUser.value = JSON.parse(userStr)
      isAdmin.value = currentUser.value?.role === 'admin'
      isDoctor.value = currentUser.value?.role === 'doctor'
    }



    // 获取轮播图数据
    const loadCarouselData = async () => {
      try {
        const result = await mockAPI.getCarousel()
        if (result.success) {
          carouselData.value = result.data
        }
      } catch (error) {
        console.error('获取轮播图失败:', error)
      }
    }

    // 获取最近预约
    const loadRecentAppointments = async () => {
      try {
        if (isDoctor.value) {
          // 医生查看自己的病人
          const result = await mockAPI.getAllAppointments()
          if (result.success) {
            const doctorPatients = result.data.filter(appointment => 
              appointment.doctorId === currentUser.value?.id
            )
            recentAppointments.value = doctorPatients.slice(0, 3) // 只显示最近3个
          }
        } else if (isAdmin.value) {
          // 管理员查看系统概览
          const result = await mockAPI.getSystemStatistics()
          if (result.success) {
            const stats = result.data
            adminStats.value = [
              {
                title: '总用户数',
                value: stats.totalUsers,
                icon: 'User',
                color: '#409EFF'
              },
              {
                title: '总预约数',
                value: stats.totalAppointments,
                icon: 'Calendar',
                color: '#67C23A'
              },
              {
                title: '待确认',
                value: stats.pendingAppointments,
                icon: 'Clock',
                color: '#E6A23C'
              },
              {
                title: '已确认',
                value: stats.confirmedAppointments,
                icon: 'Check',
                color: '#909399'
              }
            ]
          }
        } else {
          // 患者查看自己的预约
          const result = await mockAPI.getUserAppointments(currentUser.value?.id)
          if (result.success) {
            recentAppointments.value = result.data.slice(0, 3) // 只显示最近3个
          }
        }
      } catch (error) {
        console.error('获取预约记录失败:', error)
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'cancelled': '已取消',
        'completed': '已完成'
      }
      return statusMap[status] || status
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'confirmed': 'success',
        'cancelled': 'danger',
        'completed': 'info'
      }
      return typeMap[status] || 'info'
    }

    // 导航方法
    const goToDepartments = () => {
      router.push('/departments')
    }

    const goToAppointment = () => {
      router.push('/departments')
    }

    const goToMyAppointments = () => {
      if (isAdmin.value) {
        router.push('/admin')
      } else if (isDoctor.value) {
        router.push('/doctor-patients')
      } else {
        router.push('/my-appointments')
      }
    }

    const goToAIQuestion = () => {
      router.push('/ai-question')
    }

    // 查看预约详情
    const viewAppointmentDetail = (appointmentId) => {
      router.push(`/my-appointments?appointment=${appointmentId}`)
    }

    // 用户操作
    const handleCommand = async (command) => {
      if (command === 'logout') {
        try {
          await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          localStorage.removeItem('user')
          router.push('/login')
          ElMessage.success('已退出登录')
        } catch {
          // 用户取消
        }
      } else if (command === 'profile') {
        router.push('/profile')
      } else if (command === 'admin') {
        router.push('/admin')
      }
    }

    onMounted(() => {
      loadCarouselData()
      loadRecentAppointments()
    })

    return {
      carouselData,
      recentAppointments,
      currentUser,
      isAdmin,
      isDoctor,
      adminStats,
      getStatusText,
      getStatusType,
      goToDepartments,
      goToAppointment,
      goToMyAppointments,
      goToAIQuestion,
      viewAppointmentDetail,
      handleCommand
    }
  }
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: white;
}

.username {
  margin: 0 8px;
  font-size: 16px;
}

.carousel-section {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.carousel-item {
  height: 200px;
  border-radius: 10px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.carousel-content {
  text-align: center;
  color: white;
  padding: 20px;
  max-width: 80%;
}

.carousel-content h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.carousel-content p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.quick-actions {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.action-item {
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  border-radius: 15px;
}

.action-item:hover {
  transform: translateY(-5px);
}

.action-content {
  text-align: center;
  padding: 10px;
}

.action-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 15px;
}

.action-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.action-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.recent-appointments,
.health-tips {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.appointment-list {
  border: none;
  border-radius: 15px;
}

.appointment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.appointment-item:last-child {
  border-bottom: none;
}

.appointment-item:hover {
  background-color: #f8f9fa;
}

.appointment-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doctor-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.doctor-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.doctor-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.department-name {
  font-size: 14px;
  color: #666;
}

.appointment-time {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #999;
}

.appointment-status {
  flex-shrink: 0;
}

.appointment-status.pending {
  background-color: #fff3cd;
  color: #856404;
}

.appointment-status.confirmed {
  background-color: #d1ecf1;
  color: #0c5460;
}

.appointment-status.cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.appointment-status.completed {
  background-color: #d4edda;
  color: #155724;
}

.admin-overview {
  padding: 20px 0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 10px;
  margin-bottom: 10px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.tips-content {
  border: none;
  border-radius: 15px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-item:hover {
  background-color: #e3f2fd;
  transform: translateX(5px);
}

.tip-icon {
  margin-right: 15px;
  color: #409EFF;
  font-size: 24px;
  margin-top: 2px;
}

.tip-content {
  flex: 1;
}

.tip-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.tip-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .action-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .action-item {
    padding: 20px 15px;
  }
  
  .action-icon {
    font-size: 30px;
  }
  
  .action-text {
    font-size: 14px;
  }
}
</style> 